<script setup lang="ts">
import { ref } from 'vue'
import { timeFormat, timeFormat_2 } from '@/hooks/util'
import { useRoute, useRouter } from 'vue-router'
import * as cardCouponsApi from '@/api/cardCoupons'
import { message } from 'ant-design-vue'
import OkAuthorization from './components/OkAuthorization.vue'

const router = useRouter()

const okAuthorizationRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  userNick?: string | undefined
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '用户ID',
    key: 'userId',
    width: 180,
  },
  {
    title: '用户昵称',
    key: 'userNick',
    width: 180,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '过期时间',
    key: 'expiresIn',
    width: 180,
  },
  {
    key: 'action',
    title: '操作',
    width: 150,
    fixed: 'right',
  },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await cardCouponsApi.nineOnePageList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => {
  getList()
})

defineExpose({
  getList,
})

// 查询
const formRef = ref()
interface FormState {
  userNick?: string
}
const formState = reactive<FormState>({})

const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.validate().then(() => {
    if (formState.userNick != '') {
      searchParams.value.userNick = formState.userNick
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'userNick')
  getList()
}

// 91卡券授权
const toAuthorization = async () => {
  okAuthorizationRef.value.showModal()
  try {
    let { state, data, message: msg } = await cardCouponsApi.getNineOneAuthorize()
    if (state === 200) {
      window.open(data)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('获取91卡券授权链接失败~')
  }
}

// 同步卡券
const syncCoupons = async (userId: string) => {
  try {
    let { state, message: msg } = await cardCouponsApi.synchronizationCardRollNineOneData({
      userId,
    })
    if (state == 200) {
      message.success('同步请求发送成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('同步失败~')
  }
}

const changeRouter = () => {
  router.push('/nine-one-category-list')
}
</script>

<template>
  <div>
    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="formState">
        <a-form-item label="用户昵称" name="userNick">
          <a-input v-model:value="formState.userNick" placeholder="用户昵称" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button type="primary" @click="toAuthorization">91卡券授权</a-button>
        </a-form-item>
      </a-form>
    </div>

    <a-alert
      description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
      type="info"
      banner
      style="margin-bottom: 10px; padding: 10px"
    />

    <a-table
      style="overflow-x: scroll"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="changePage"
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
      :scroll="{ x: 100 }"
      size="small"
    >
      <template #emptyText>
        <a-empty description="暂无数据" />
      </template>

      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'userId'">
          {{ record.couponUserId }}
        </template>

        <template v-else-if="column.key === 'userNick'">
          {{ record.userNick }}
        </template>

        <template v-else-if="column.key === 'createTime'">
          {{ timeFormat_2(record.createTime) }}
        </template>

        <template v-else-if="column.key === 'expiresIn'">
          {{ timeFormat_2(record.expiresIn) }}
        </template>

        <template v-else-if="column.key === 'action'">
          <div style="width: 100px; margin: 0; padding: 0">
            <a @click="changeRouter">卡种列表</a>
          </div>
        </template>
      </template>
    </a-table>

    <OkAuthorization ref="okAuthorizationRef" @refresh="getList"></OkAuthorization>
  </div>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
